package com.commerce.networkframework.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.TextUtils;
import android.widget.TextView;

import com.commerce.networkframework.Entity.ValuePair;
import com.commerce.networkframework.R;
import com.commerce.networkframework.utlis.StreamToString;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class HttpURLConnectionActivity extends AppCompatActivity {

    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_httpurl_connection);
        textView = findViewById(R.id.hcn_json);
        new Thread(new Runnable() {
            @Override
            public void run() {
                   useHttpUrlConnectionPost();
            }
        }).start();
    }

    /**
     * 配置HttpURLConnection默认参数
     * @param url
     * @return  HttpURLConnection
     */
    private static HttpURLConnection getHttpURLConnection( String url){
        HttpURLConnection httpURLConnection = null;
        try {
            URL mUrl = new URL(url);
            httpURLConnection = (HttpURLConnection) mUrl.openConnection();
            //设置连接超时时间
            httpURLConnection.setConnectTimeout(15*1000);
            //设置读取超时时间
            httpURLConnection.setReadTimeout(15*1000);
            //设置请求方式
            httpURLConnection.setRequestMethod("POST");
            //添加消息报头
            httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            //打开输入流
            httpURLConnection.setDoInput(true);
            //打开输出流（传递参数时需要开启）
            httpURLConnection.setDoOutput(true);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return httpURLConnection;
    }

    /**
     * 组织请求参数写入输出流
     * @param output
     * @param pairList    参数实体类队列
     * @throws IOException
     */
    private static void PostParams(OutputStream output, List<ValuePair> pairList) throws IOException {
        StringBuilder mStringBuilder = new StringBuilder();
        
        for (ValuePair pair:pairList){
            if (!TextUtils.isEmpty(mStringBuilder)) {
                 mStringBuilder.append("&");
            }
            mStringBuilder.append(URLEncoder.encode(pair.getName(),"UTF-8"));
            mStringBuilder.append("=");
            mStringBuilder.append(URLEncoder.encode(pair.getValue(),"UTF-8"));
        }
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, "UTF-8"));
        writer.write(mStringBuilder.toString());
        writer.flush();
        writer.close();

    }

    /**
     * HttpURLConnection进行请求
     */
    private void useHttpUrlConnectionPost(){
        HttpURLConnection mHttpURLConnection = getHttpURLConnection("http://apis.juhe.cn/simpleWeather/cityList");
        List<ValuePair> postParams = new ArrayList<>();
        postParams.add(new ValuePair("key","7b3a2993da15202e95aa1e78e4e0799c"));
        try {
            PostParams(mHttpURLConnection.getOutputStream(),postParams);
            mHttpURLConnection.connect();
            InputStream inputStream = mHttpURLConnection.getInputStream();
            final String str = new StreamToString().conStreamToString(inputStream);
            runOnUiThread(new Thread(new Runnable() {
                @Override
                public void run() {
                textView.setText(str);
                }
            }));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}